package com.keepalive_kotlin.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.blankj.utilcode.util.LogUtils
import com.keepalive_kotlin.manager.KeepAliveManager

/**
 * 保活广播接收器
 * 监听系统事件以重启保活服务
 */
class KeepAliveReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        LogUtils.i("$TAG 接收到广播: $action")
        
        when (action) {
            Intent.ACTION_BOOT_COMPLETED -> {
                // 设备启动完成，启动保活服务
                LogUtils.i("$TAG 设备启动完成")
                startKeepAliveService(context)
            }
            Intent.ACTION_MY_PACKAGE_REPLACED -> {
                // 应用更新完成，启动保活服务
                LogUtils.i("$TAG 应用更新完成")
                startKeepAliveService(context)
            }
            Intent.ACTION_SCREEN_ON -> {
                // 屏幕点亮，可以做一些检查
                LogUtils.i("$TAG 屏幕点亮")
            }
            Intent.ACTION_USER_PRESENT -> {
                // 用户解锁设备
                LogUtils.i("$TAG 用户解锁设备")
            }
            Intent.ACTION_SCREEN_OFF -> {
                // 屏幕关闭，启动1像素Activity
                LogUtils.i("$TAG 屏幕关闭")
                KeepAliveManager.getInstance().startOnePixelActivity(context)
            }
            else -> {
                LogUtils.w("$TAG 未处理的广播: $action")
            }
        }
    }

    /**
     * 启动保活服务
     */
    private fun startKeepAliveService(context: Context) {
        try {
            KeepAliveManager.getInstance().startKeepAliveService(context)
        } catch (e: Exception) {
            LogUtils.e("$TAG 启动保活服务失败: ${e.message}")
        }
    }

    companion object {
        private const val TAG = "KeepAliveReceiver"
    }
}